package initialize

import (
	"api/global"
	"fmt"
	"github.com/hashicorp/consul/api"
	"strconv"
)

func InitConsul() *api.Client {

	config := api.DefaultConfig()

	config.Address = "113.44.72.167:8500"

	// Get a new client
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}

	return client
}

// 查询consul服务
func FindGoodsServer() (string, string) {

	service, q, err := global.ConsulApi.Catalog().Service("/goods_srv", "", nil)
	if err != nil {
		fmt.Println("未找到服务", err)
		return "", ""
	}
	fmt.Println(service, q)

	fmt.Println("找到的服务：")
	var address string
	var port int

	for _, v := range service {
		address = v.Address
		port = v.ServicePort

		fmt.Printf("ID:%s\nName:%s\n地址:%s\n端口:%d\n",
			v.ServiceID, v.ServiceName, v.Address, v.ServicePort)

	}

	Port := strconv.Itoa(port)

	return address, Port
}
